<?php

	function GetLatestLocations($BDD_connexion)
	{
		
		$LATEST_NUMBER = 4;
		
		$locations = array();

		$request = "SELECT DISTINCT bien.id_bien,bien.nom,bien.categorie FROM bien,location WHERE location.ref_bien = bien.id_bien ORDER BY added_timestamp DESC LIMIT 0,:latest_number";
		$prepare=$BDD_connexion->prepare($request);
		$prepare->bindValue(':latest_number',$LATEST_NUMBER,PDO::PARAM_INT);
		$prepare->execute();
		while($location=$prepare->fetch(PDO::FETCH_OBJ))
		{
			$location->description = getLocationDescription($BDD_connexion,$location->id_bien);
			$location->notation = getLocationNotation($BDD_connexion,$location->id_bien);
			$locations[] = $location;
		}

		return $locations;
	}
	
	function GetMostPopularsLocations($BDD_connexion)
	{
		
		$RECOMMENDED_NUMBER = 4;
		
		$nonOrderedLocations = array();
		$orderedLocations = array();
		$popularslocations = array();

		$request = "SELECT DISTINCT bien.id_bien,bien.nom,bien.categorie FROM bien,location WHERE location.ref_bien = bien.id_bien";
		$prepare=$BDD_connexion->prepare($request);
		$prepare->bindValue(':number',$RECOMMENDED_NUMBER,PDO::PARAM_INT);
		$prepare->execute();
		while($location=$prepare->fetch(PDO::FETCH_OBJ))
		{
			$location->description = getLocationDescription($BDD_connexion,$location->id_bien);
			$location->notation = getLocationNotation($BDD_connexion,$location->id_bien);
			$nonOrderedLocations[] = $location;
		}
				
		$orderedLocations = orderLocationsByNotation($nonOrderedLocations);
		
		for ($i=0; $i < min($RECOMMENDED_NUMBER,count($orderedLocations)); $i++)
		{
			$popularslocations[$i] = $orderedLocations[$i];
		}

		return $popularslocations;
	}
	
	function orderLocationsByNotation($locations)
	{
		
		$orderedLocations_temp = array();
		$locations_temp = array_values($locations);
		
		$size = count($locations_temp);
		$indexArray = 0;
		
		while ($indexArray < $size)
		{
			$maxIndex = getMaxNotationIndex($locations_temp);
			$orderedLocations_temp[$indexArray] = $locations_temp[$maxIndex];
			unset($locations_temp[$maxIndex]);
			$locations_temp = array_values($locations_temp);
			$indexArray++;
		}
		
		return $orderedLocations_temp;
	
	}
	
	function getMaxNotationIndex($locations)
	{
	
		$maxIndex = 0;
		
		for ($i=0; $i < count($locations); $i++)
		{
			if ($locations[$i]->notation > $locations[$maxIndex]->notation)
			{
				$maxIndex = $i;
			}
		}
		
		return $maxIndex;
		
	}
	
?>
